//
//  MyTableViewController.m
//  CoreData
//
//  Created by ibokan on 14-11-4.
//  Copyright (c) 2014年 ibokan. All rights reserved.
//

#import "MyTableViewController.h"
#import "AppDelegate.h"
#import "Person.h"
#import "MyViewController.h"
#import "Header.h"
@interface MyTableViewController ()
@property(strong,nonatomic)NSMutableArray *names;
@property(strong,nonatomic)NSMutableDictionary *nameIndexs;
@property(strong,nonatomic)NSMutableArray *keys;
@end

@implementation MyTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIApplication *app = [UIApplication sharedApplication];
    AppDelegate *delegate= app.delegate ;
    self.managedObjectContext = delegate.managedObjectContext;
    
    
    NSFetchRequest *requst = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
    self.persons = [[self.managedObjectContext executeFetchRequest:requst error:nil] mutableCopy];

    
    self.names = [NSMutableArray arrayWithCapacity:60];
    for (Person *p in self.persons) {
        [self.names addObject:p.name];
    }
#warning add something
#pragma 为每个组里面的单元行进行排序
    [self.names sortUsingSelector:@selector(compare:)];
    
    
    self.nameIndexs = [NSMutableDictionary dictionaryWithCapacity:26];
    for (char character = 'a'; character <= 'z'; character++) {
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:50];
        [self.nameIndexs setObject:arr forKey:[NSString stringWithFormat:@"%c",character]];
    }
    
    for (NSString *n in self.names) {
        NSString *initial = [NSString stringWithFormat:@"%c",pinyinFirstLetter([n characterAtIndex:0])];
        
        [self.nameIndexs[initial] addObject:n];
    }
    
    //将空组去掉
    for (char character = 'a'; character <= 'z'; character++) {
        NSString *key = [NSString stringWithFormat:@"%c",character];
        NSArray *arr = self.nameIndexs[key];
        if (arr.count == 0) {
            [self.nameIndexs removeObjectForKey:key];
        }
    }
<<<<<<< HEAD
    
   
    
    
    self.keys = [[self.nameIndexs allKeys]mutableCopy];
    
    self.keys = [[self.keys sortedArrayUsingSelector:@selector(compare:)]mutableCopy];
=======
    self.keys = [[self.nameIndexs allKeys] mutableCopy];
    
    self.keys = [[self.keys sortedArrayUsingSelector:@selector(compare:)] mutableCopy];
>>>>>>> 432242c8188447b38622c69b562684968c675268
    [self.keys sortedArrayUsingSelector:@selector(compare:)];
    
    for (int i = 0;i < self.keys.count;i++) {
        NSLog(@"%@",self.keys[i]);
    }
    
    
//    [self refresh];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshTheData:) name:@"SAVE" object:nil];
    
}

-(void)dealloc{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center removeObserver:self name:@"SAVE" object:nil];
}

//-(void)didTheSave{
//    NSLog(@"SAVE DONE");
//    [self refresh];
//    [self.tableView reloadData];
//}

- (IBAction)editPressed:(UIBarButtonItem *)sender {
    [self.tableView setEditing:!self.tableView.editing animated:YES];
}

-(void)refreshTheData:(NSNotification *)notification{
    NSFetchRequest *requst = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
    self.persons = [[self.managedObjectContext executeFetchRequest:requst error:nil] mutableCopy];
    

    
    for (Person *p in self.persons) {
        NSLog(@"%@",p.name);
    }
    
    
    
    
    if (notification != nil) {
        [self.names removeAllObjects];
        [self.nameIndexs removeAllObjects];
        for (char character = 'a'; character <= 'z'; character++) {
            NSMutableArray *arr = [NSMutableArray arrayWithCapacity:50];
            [self.nameIndexs setObject:arr forKey:[NSString stringWithFormat:@"%c",character]];
        }
        for (Person *p in self.persons) {
//            [self.names removeAllObjects];
            [self.names addObject:p.name];
        }
        
#warning add something
        [self.names sortUsingSelector:@selector(compare:)];
        
        for (NSString *n in self.names) {
            NSString *initial = [NSString stringWithFormat:@"%c",pinyinFirstLetter([n characterAtIndex:0])];
//            [self.nameIndexs removeAllObjects];
            [self.nameIndexs[initial] addObject:n];
        }
        for (char character = 'a'; character <= 'z'; character++) {
            NSString *key = [NSString stringWithFormat:@"%c",character];
            NSArray *arr = self.nameIndexs[key];
            if (arr.count == 0) {
                [self.nameIndexs removeObjectForKey:key];
            }
        }
        NSLog(@"%@",self.nameIndexs);
<<<<<<< HEAD
        self.keys = [[self.nameIndexs allKeys]mutableCopy];
        self.keys = [[self.keys sortedArrayUsingSelector:@selector(compare:)]mutableCopy];
=======
        self.keys = [[self.nameIndexs allKeys] mutableCopy];
        self.keys = [[self.keys sortedArrayUsingSelector:@selector(compare:)] mutableCopy];
>>>>>>> 432242c8188447b38622c69b562684968c675268
    }
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return self.keys.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *key = self.keys[section];
    NSArray *arr = self.nameIndexs[key];
    return arr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
   
    NSString *key = self.keys[indexPath.section];
    NSArray *nameArray = self.nameIndexs[key];
    NSString *nameForSearch = nameArray[indexPath.row];
    
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
    
    //指定查询条件
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",nameForSearch];
    
    [request setPredicate:predicate];
    
    NSArray *arr = [self.managedObjectContext executeFetchRequest:request error:nil];
    if (arr.count != 0) {
        
       Person *person = arr[0];
    
    
    
    UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:1];
    UILabel *phoneNoLabel = (UILabel *)[cell.contentView viewWithTag:2];
    UIImageView *imageView = (UIImageView*)[cell.contentView viewWithTag:3];
   
    
    NSString *imagePath = person.imagePath;
    if (imagePath == nil) {
        UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"pie" ofType:@"png"]];
        [imageView setImage:img];
    }else{
        UIImage *img = [UIImage imageWithContentsOfFile:imagePath];
        [imageView setImage:img];
    }
    nameLabel.text = person.name;
        phoneNoLabel.text = person.phoneNo;
    }
    return cell;

}


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return YES;
}








// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
<<<<<<< HEAD
    
    NSMutableArray *deleArray = [self.nameIndexs objectForKey:[self.keys objectAtIndex:indexPath.section]];
=======
    NSMutableArray *deleArray = [NSMutableArray arrayWithArray:[self.nameIndexs objectForKey:[self.keys objectAtIndex:indexPath.section]]];
>>>>>>> 432242c8188447b38622c69b562684968c675268
    
    NSString *deleName = deleArray[indexPath.row];
    //获得实体名为Student所有数据
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
    
    //指定查询条件
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",deleName];
    
    [request setPredicate:predicate];
    
    Person *person = [self.managedObjectContext executeFetchRequest:request error:nil][0];
    NSLog(@"%@",person.name);
    NSLog(@"section = %ld,row = %ld",indexPath.section,indexPath.row);
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
       [self.managedObjectContext deleteObject:person];
        
//        [self refreshTheData:nil];
        
        
        
        /***********
         * tableView 删除row或者删除section，首先要把你的数据源（也就是对应的你的array或者dictionary）中对应的数据删除掉，然后再进行delete操作
         * 你在做删除操作的时候你要考虑，假如你删除的row是所在section中的最后一个单元，那么当这个row被删除后，此section也应该不存在了，尤其是你加入了索引。
         ***********/
        [deleArray removeObjectAtIndex:indexPath.row];
        
        [self.nameIndexs setObject:deleArray forKey:[self.keys objectAtIndex:indexPath.section]];
        
<<<<<<< HEAD
=======
#warning    这个地方有错误
        /***********
         * tableView 删除row或者删除section，首先要把你的数据源（也就是对应的你的array或者dictionary）中对应的数据删除掉，然后再进行delete操作
         * 你在做删除操作的时候你要考虑，假如你删除的row是所在section中的最后一个单元，那么当这个row被删除后，此section也应该不存在了，尤其是你加入了索引。
         ***********/
        [deleArray removeObjectAtIndex:indexPath.row];
        
        [self.nameIndexs setObject:deleArray forKey:[self.keys objectAtIndex:indexPath.section]];
        
>>>>>>> 432242c8188447b38622c69b562684968c675268
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

        if (deleArray.count == 0) {
            [self.keys removeObjectAtIndex:indexPath.section];
            [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        
        
        
        
        if (deleArray.count == 0) {
            [self.keys removeObjectAtIndex:indexPath.section];
            [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
        }

        
//        [self.persons removeObject:person];
        
        if ([self.managedObjectContext save:nil]) {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"删除成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alertView show];
        }
        
//#warning    这个地方有错误
//        [tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        
        
        
    }
}


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    self.tableView.editing = NO;
    MyViewController *myViewController = segue.destinationViewController;
    if ([segue.identifier isEqualToString:@"update"]) {
        NSIndexPath *indexpath = [self.tableView indexPathForSelectedRow];
        //得到学生

        NSString *key = self.keys[indexpath.section];
        NSArray *namesArray = [self.nameIndexs objectForKey:key];
        NSString *selectedName = namesArray[indexpath.row];
        
        //获得实体名为Student所有数据
        NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
        
        //指定查询条件
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",selectedName];
        [request setPredicate:predicate];
        Person *person = [self.managedObjectContext executeFetchRequest:request error:nil][0];
        myViewController.myTableViewController = self;
        myViewController.name = person.name;
       
    }
}



-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{                    //索引
    return self.keys;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString *key = self.keys[section];
    return key;
}





@end
